import Express from "express";

import UserService from "../../service/UserService";
import ResponseHelper, {
  ResponseBody,
  ResponseCode,
} from "../utils/ResponseHelper";
import { publish } from "../jwt";
import { ITokenRequest } from "../tokenMiddleware";

const router = Express.Router();

router.get("/whoami", async (req: ITokenRequest, res, next) => {
  const { UID, EMAIL } = req;

  try {
    const result = await UserService.whoami({ id: UID, email: EMAIL });
    handlepublishToken(result, res);
    ResponseHelper.send(result, res, req);
  } catch (err) {
    next(err);
  }
});

router.post("/login", async (req, res, next) => {
  try {
    const result = await UserService.login(req.body);
    handlepublishToken(result, res);
    ResponseHelper.send(result, res, req as ITokenRequest);
  } catch (err) {
    next(err);
  }
});

router.post("/register", async (req, res, next) => {
  try {
    const result = await UserService.register(req.body);
    handlepublishToken(result, res);
    ResponseHelper.send(result, res, req as ITokenRequest);
  } catch (err) {
    next(err);
  }
});

// 修改密码
router.put("/modifyPassword", async (req, res, next) => {
  try {
    const result = await UserService.modifyPassword(req.body);
    ResponseHelper.send(result, res, req as ITokenRequest);
  } catch (err) {
    next(err);
  }
});

function handlepublishToken(result: ResponseBody, res: Express.Response) {
  if (result.code === ResponseCode.PASS) {
    publish(res, 3600 * 24 * 7, {
      id: result.data["id"],
      email: result.data["email"],
    });
  }
}

export default router;
